﻿using System;
using System.Collections.Generic;

namespace CompositePattern;

// 组合模式
public interface IComponent
{
    string Name { get; set; }
    void Add(IComponent component);
    void Remove(IComponent component);
    void Display(int depth);
}

public class File(string name) : IComponent
{
    public string Name { get; set; } = name;

    public void Add(IComponent component)
    {
        Console.WriteLine("不能在文件作为父级的情况下添加文件");
    }

    public void Remove(IComponent component)
    {
        Console.WriteLine("不能在文件作为父级的情况下删除文件");
    }

    public void Display(int depth)
    {
        Console.WriteLine(new string(' ', depth * 4) + "|-- " + Name);
    }
}

public class Directory(string name) : IComponent
{
    public string Name { get; set; } = name;
    private readonly List<IComponent> _components = [];

    public void Add(IComponent component)
    {
        _components.Add(component);
    }

    public void Remove(IComponent component)
    {
        _components.Remove(component);
    }

    public void Display(int depth)
    {
        Console.WriteLine(new string(' ', depth * 4) + "+-- " + Name);

        foreach (IComponent component in _components)
        {
            component.Display(depth + 1);
        }
    }
}

public static class Program
{
    public static void Main()
    {
        // 创建文件和目录
        IComponent rootDir = new Directory("Root");
        IComponent homeDir = new Directory("Home");
        IComponent userDir = new Directory("User");
        IComponent photosDir = new Directory("Photos");
        IComponent doc1 = new File("Document1.txt");
        IComponent pic1 = new File("Picture1.jpg");

        // 构建并显示文件目录结构
        rootDir.Add(homeDir);
        homeDir.Add(userDir);
        userDir.Add(photosDir);
        userDir.Add(doc1);
        photosDir.Add(pic1);
        rootDir.Display(0);
        Console.WriteLine("-----------------");
        //删除并显示文件目录结构
        photosDir.Remove(pic1);
        rootDir.Display(0);
    }
}